package com.voodoo.lib_crashexception;

import android.content.Context;

import androidx.annotation.NonNull;

import com.voodoo.lib_crashexception.model.CrashModel;
import com.voodoo.lib_crashexception.utils.CrashUtil;

/**
 * Author: voodoo
 * CreateDate: 2021/05/16
 * Description: 拦截异常信息
 */
public class CrashException implements Thread.UncaughtExceptionHandler {

    private static Context mContext;
    public static OnCrashExceptionListener mOnCrashExceptionListener;

    public CrashException() {
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    /**
     * 初始化异常捕捉工具类
     *
     * @param context                  上下文
     * @param onCrashExceptionListener 异常监听
     * @return {@link CrashException}
     */
    public static CrashException init(Context context, OnCrashExceptionListener onCrashExceptionListener) {
        mContext = context;
        mOnCrashExceptionListener = onCrashExceptionListener;
        return new CrashException();
    }

    public static Context getContext() {
        return mContext;
    }

    /**
     * 拦截异常信息
     *
     * @param thread    异常线程
     * @param throwable 异常信息
     */
    @Override
    public void uncaughtException(@NonNull Thread thread, @NonNull Throwable throwable) {
        handleException(throwable);
    }

    private void handleException(Throwable throwable) {
        CrashModel crashModel = CrashUtil.parseCrash(throwable);
        System.out.println(String.format("捕获的异常对象\n%s", crashModel));

        if (mOnCrashExceptionListener != null) {
            mOnCrashExceptionListener.onCrashException(crashModel);
        }
    }

    public interface OnCrashExceptionListener {
        void onCrashException(CrashModel crashModel);
    }

}
